<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :visible="visible"
    :mask-closable="false"
    :destroy-on-close="true"
    @close="onClose"
  >
    <div style="position: relative">
      <TaskTitle :icon-name="iconName" :title-name="titleName" :color="color" />
      <p-button
        v-if="isEdit || !addState"
        class="commonbutton edit"
        type="primary"
        @click="edit"
      >
        编辑
      </p-button>
    </div>
    <div class="g-drawer-list-container" style="overflow-x: hidden">
      <TitleSecondary title="基本信息" />
      <AddVisitForm
        ref="form"
        :form="form"
        :is-foot="isFoot"
        :add-state="addState"
        :customer-code.sync="customerCode"
        :delete-file-id.sync="deleteFileId"
        :business-keys.sync="businessKeys"
        :cur-keys.sync="curKeys"
        :select-cur.sync="selectCur"
        :select-business.sync="selectBusiness"
      />
      <TitleSecondary title="线索" />
      <clueTable
        :select-cur.sync="selectCur"
        :cur-keys.sync="curKeys"
        @add-clue="addClue"
      />
      <TitleSecondary title="商机" />
      <!-- <ButtonGroup
        :options="clueButtons"
        style="margin-bottom: 20px"
        @click="handleButtonClick"
      /> -->
      <businessTable
        ref="business"
        :select-business.sync="selectBusiness"
        :business-keys.sync="businessKeys"
        @delet-dusiness="deletDusiness"
        @add-business="addBusiness"
      />
    </div>
    <ButtonGroup
      class="g-drawer-footer"
      :options="footerButtons"
      @click="handleButtonClick"
    />
    <DialogVisitBusinessList
      ref="business"
      :visible.sync="visibleBusiness"
      :datasource-business="datasourceBusiness"
      :customer-code="customerCode"
      :select-business.sync="selectBusiness"
      :business-keys.sync="businessKeys"
    />
    <DialogVisitClueList
      ref="clue"
      :customer-code="customerCode"
      :visible.sync="visibleClue"
      :select-cur.sync="selectCur"
      :cur-keys.sync="curKeys"
    />
  </p-drawer>
</template>

<script>
import monent from 'moment';
import DialogVisitBusinessList from '@/components/dialog/DialogVisitBusinessList.vue';
import DialogVisitClueList from '@/components/dialog/DialogVisitClueList.vue';
import AddVisitForm from './AddVisitForm.vue';
import clueTable from './clueTable.vue';
import businessTable from './businessTable.vue';
import {
  postAddVisit,
  getBusinessDetail,
  getClueFollowDetails,
} from '@/api/visit.js';
import { getCurrentUser } from '@/api/public.js';

const defaultForm = {
  id: '',
  visitNo: '',
  visitName: '',
  visitTime: '',
  visitStyle: '',
  department: '',
  customerName: '',
  customerCode: '',
  visitType: '',
  emergencyLevel: '',
  executionStatus: '0',
  address: '',
  remark: '',
  createUserName: '',
  updateTime: '',
  updateUserName: '',
  createTime: '',
  updateUserDepartmentName: '',
  createUserDepartmentName: '',
  leadsList: [],
  opportunityList: [],
  logList: [],
};
export default {
  components: {
    AddVisitForm,
    clueTable,
    businessTable,
    DialogVisitBusinessList,
    DialogVisitClueList,
  },
  // mixins: [DrawerMixin],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    addState: {
      type: Boolean,
      default: false,
    },
    detail: {
      type: Object,
      default: () => ({}),
    },
    isFoot: {
      type: Boolean,
      default: false,
    },
    titleInfo: {
      type: Object,
      default: () => ({}),
    },
    leadsNo: {
      type: String,
      default: '',
    },
    opportunityNo: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      form: {
        ...defaultForm,
      },
      titleName: '拜访详情',
      color: 'green',
      iconName: 'Det',
      planIdNew: undefined,
      saleList: [],
      isEdit: false,
      currentUser: '',
      currentUserOrg: '',
      isSave: false,
      deleteFileId: [],
      visibleClue: false,
      visibleBusiness: false,
      customerCode: '',
      loadingCur: false,
      selectCur: [],
      curKeys: [],
      selectBusiness: [],
      businessKeys: [],
      load: false,
    };
  },

  computed: {
    curId() {
      const result = this.selectCur.reduce((pre, cur) => {
        pre.push(cur.leadsNo);
        return pre;
      }, []);
      return result;
    },
    businessId() {
      const result = this.selectBusiness.reduce((pre, cur) => {
        pre.push(cur.opportunityNo);
        return pre;
      }, []);
      return result;
    },
    footerButtons() {
      const buttons = this.addState
        ? [
            {
              key: 'save',
              type: 'primary',
              label: '保存',
              auth: true,
            },
            {
              key: 'close',
              label: '返回',
            },
          ]
        : [
            {
              key: 'close',
              label: '返回',
            },
          ];
      return buttons;
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (!val) return;
        if (this.detail.type === 'routerAdd') {
          this.form.customerName = this.detail.customerName;
          this.form.customerCode = this.detail.customerCode;
          this.customerCode = this.detail.customerCode;
        }
      },
    },
    titleInfo: {
      handler(val) {
        this.titleName = val.titleName;
        this.color = val.color;
        this.iconName = val.iconName;
      },
      immediate: true,
    },
    leadsNo: {
      async handler(val) {
        if (val) {
          const result = await getClueFollowDetails(val);
          const detail = result?.data?.data || {};
          this.selectCur = [detail] || [];
          // this.selectCur=[{}]
          this.form.customerName = detail.customerShortName;
          this.form.customerCode = detail.customerCode;
          this.customerCode = detail.customerCode;
        }
      },
      immediate: true,
    },
    opportunityNo: {
      async handler(val) {
        if (val) {
          const result = await getBusinessDetail(val);
          console.log('result: ', result);
          const detail = result?.data?.data || {};
          this.selectBusiness = [detail] || [];
          // this.selectCur=[{}]
          this.form.customerName = detail.customerShortName;
          this.form.customerCode = detail.customerCode;
          this.customerCode = detail.customerCode;
        }
      },
      immediate: true,
    },
  },
  created() {
    this.getCurrentInfo();
  },
  methods: {
    // clueList() {
    //   this.getClueList();
    // },

    // async getClueList() {
    //   const customerCode = this.$refs.form.form.customerCode;
    //   console.log('customerCode: ', customerCode);
    //   const form = this.$refs.clue.form;
    //   const data = {
    //     current: 1,
    //     pageSize: 10,
    //     customerCode: customerCode,
    //     ...form,
    //   };
    //   this.visibleClue = true;
    //   this.load = true;
    //   const result = await postClueTableList(data).finally(
    //     () => (this.load = false)
    //   );
    //   this.datasourceCur = result?.data?.data?.records || [];
    // },
    async addClue() {
      const customerName = this.$refs.form.form.customerName;
      if (!customerName) {
        this.$message.error('请选择客户简称后点击关联');
        return;
      }
      this.visibleClue = true;
    },
    async addBusiness() {
      const customerName = this.$refs.form.form.customerName;
      if (!customerName) {
        this.$message.error('请选择客户简称后点击关联');
        return;
      }
      this.visibleBusiness = true;
    },
    deletDusiness() {
      console.log('我是删除');
    },
    async edit() {
      console.log('??????????');
      this.titleName = '编辑拜访';
      this.color = 'blue';
      this.iconName = 'Edit';
      this.isSave = true;
      this.$emit('update:addState', true);
      this.isEdit = false;
    },
    async getCurrentInfo() {
      const result = await getCurrentUser();
      console.log('result: ', result);
      this.currentUser = result?.data?.data?.name || '';
      this.currentUserOrg = result?.data?.data?.departmentName || '';
      this.currentUserOrg = this.removalSame(this.currentUserOrg);
    },
    removalSame(obj) {
      obj = obj.replace(/\s*/g, '');
      const array = obj.split(',');
      console.log('array: ', array);
      const departmentName = [...new Set(array)].join(',');
      return departmentName;
    },
    clearList() {
      this.saleList = [];
    },
    onClose() {
      this.titleName = '拜访详情';
      this.color = 'green';
      this.iconName = 'Det';
      this.form = { ...defaultForm };
      this.isEdit = false;
      this.selectBusiness = [];
      this.selectCur = [];
      this.deleteFileId = [];
      this.businessKeys = [];
      this.curKeys = [];
      this.$emit('update:isFoot', false);
      this.$emit('update:visible', false);
      this.$emit('fresh');
    },

    async saveCallback() {
      console.log('???????????');
      const valid = await this.$refs.form.validate();
      if (!valid) return new Promise(() => {});
      const formInfo = JSON.parse(JSON.stringify(this.$refs.form.form));
      // if (!this.$refs.form.list.length) {
      //   formInfo.attachmentList = [];
      // }
      formInfo.leadsList = this.curId;
      formInfo.opportunityList = this.businessId;
      formInfo.createUserDepartmentName = this.currentUserOrg || '';
      formInfo.updateUserDepartmentName = this.currentUserOrg || '';
      formInfo.updateUserName = this.currentUser || '';
      const result = await postAddVisit(formInfo);
      if (result.data.code === 0) {
        this.$message.success('保存成功！');
        this.closeCallback();
        this.isSave = false;
      }
    },
    businessAddCallback() {
      this.visibleVisit = true;
    },
    closeCallback() {
      this.onClose();
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
  },
};
</script>
<style lang="less" scoped>
.edit {
  position: absolute;
  top: 10px;
  right: 30px;
}
.table-list-container {
  margin-top: 20px;
  height: 390px !important;
}
</style>


